package com.iplatform.file.minio.core;


import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.minio.http.Method;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * minio客户端工具类
 *
 * @author MrRed
 * @date 2020-10-09
 */
@Slf4j
@Component
public class MinioClientHelper {

    @Autowired
    private MinioConfig minioConfig;

    private String usingMinioConfig;

    private MinioClient minioClient;

    /**
     * 获取上传文件预先签名地址
     *
     * @param objPath          文件相对路径
     * @param bucketName       桶名，如果桶名为空使用默认桶，如果桶不存在则创建桶
     * @param presignedExpires 过期时间
     */
    public String presignedPutObject(String objPath, String bucketName, Integer presignedExpires) throws Exception {
        System.out.println("进入");
        bucketName = StringUtils.isBlank(bucketName) ? minioConfig.getDefaultBucket() : bucketName;
        if (!getMinioClient().bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
        presignedExpires= presignedExpires<=0 ? 200000 : presignedExpires;
        return minioClient.presignedPutObject(bucketName, objPath, presignedExpires);
    }

    /**
     * 获取下载文件预先签名地址
     *
     * @param objPath          文件相对路径
     * @param bucketName       桶名
     * @param presignedExpires 过期时间
     */

    public String presignedGetObject(String objPath, String bucketName, Integer
            presignedExpires) throws Exception {
        if (minioClient == null) {
            initClient();
        }
        if (StringUtils.isBlank(bucketName)){
            bucketName=minioConfig.getDefaultBucket();
        }
        return minioClient.getPresignedObjectUrl(Method.GET, bucketName, objPath, presignedExpires, null);
    }




    /*
     * public String presignedGetObject(String objPath, String bucketName, Integer
     * presignedExpires) throws Exception { String a=
     * minioClient.presignedPutObject(bucketName, objPath,presignedExpires); return
     * a; }
     */

    /**
     * 获取minioclient
     */
    public MinioClient getMinioClient() throws InvalidPortException, InvalidEndpointException {
        if (minioClient == null) {
            initClient();
        }
        //如果当前使用的配置与最新配置不相同则更新minoclient
//        if (!usingMinioConfig.equals(minioClient.toString())) {
//            initClient();
//        }
//        //记录当前使用的minio配置信息
//        this.usingMinioConfig = minioConfig.toString();
        if (usingMinioConfig == null) {
            initClient();
        }
        return minioClient;
    }

    /**
     * 初始化minio
     */
    public void initClient() throws InvalidPortException, InvalidEndpointException {
        this.minioClient = new MinioClient(minioConfig.getMinioUrl(), minioConfig.getAccessKey(), minioConfig.getSecretKey());
    }


}
